package yunjiao.javatutorials.guava.base.pairwise;

import com.google.common.base.Equivalence;
import com.google.common.collect.Sets;

import java.util.Set;

/**
 * 与集合工具结合使用
 *
 * @author yangyunjiao
 */
public class SetComparisonExample {
    public static void main(String[] args) {
        // 创建基于首字符比较的 Equivalence
        Equivalence<String> firstCharEquivalence = new Equivalence<String>() {
            @Override
            protected boolean doEquivalent(String a, String b) {
                if (a == null && b == null) return true;
                if (a == null || b == null || a.isEmpty() || b.isEmpty())
                    return false;
                return a.charAt(0) == b.charAt(0);
            }

            @Override
            protected int doHash(String s) {
                return s != null && !s.isEmpty() ? s.charAt(0) : 0;
            }
        };

        Equivalence<Iterable<String>> pairwiseByFirstChar = firstCharEquivalence.pairwise();

        Set<String> set1 = Sets.newHashSet("apple", "ant", "anchor");
        Set<String> set2 = Sets.newHashSet("apricot", "animal", "angle");
        Set<String> set3 = Sets.newHashSet("banana", "berry");

        System.out.printf("set1=%s 和 set2=%s 等价: %b \n", set1.toString(), set2.toString(),
                pairwiseByFirstChar.equivalent(set1, set2)); // true
        System.out.printf("set1=%s 和 set3=%s 等价: %b \n", set1.toString(), set3.toString(),
                pairwiseByFirstChar.equivalent(set1, set3)); // false

        // 计算哈希值
        System.out.println("set1 哈希值: " + pairwiseByFirstChar.hash(set1));
        System.out.println("set2 哈希值: " + pairwiseByFirstChar.hash(set2));
    }
}
